<?php

namespace App\Listeners;

use App\Jobs\Log\ActionJob;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;

class DbListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        try {
            if (env('APP_DEBUG', false)) {
                $sql = str_replace("?", "'%s'", $event->sql);
                foreach ($event->bindings as $i => $binding) {
                    if ($binding instanceof \DateTime) {
                        $event->bindings[$i] = $binding->format('Y-m-d H:i:s');
                    } else {
                        if (is_string($binding)) {
                            $event->bindings[$i] = $binding;
                        }
                    }
                }
                $log = vsprintf($sql, $event->bindings);
                $log = $log.'  [ RunTime:'.$event->time.'ms ] ';
                (new Logger('sql'))->pushHandler(new RotatingFileHandler(storage_path('logs/sql/sql.sql')))->info($log);
            }
        } catch (\Exception $exception) {
            Log::error('SQL:ERROR-luoyongsheng：'.date('Y-m-d H:i:s'));
        }
    }
}
